using DOTS.DOD.LESSON5;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace DOTS.DOD.LESSON7
{
    [BurstCompile]
    [RequireMatchingQueriesForUpdate]
    [UpdateInGroup(typeof(CubesMarchSystemGroup))]
    public partial struct CubesGeneratorSystem : ISystem
    {
        float mTimer;
        int mCubesCount;

        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<CubeGenerator>();
            mTimer = 0f;
            mCubesCount = 0;
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var generator = SystemAPI.GetSingleton<CubeGenerator>();

            if (mCubesCount >= generator.GenerationTotalCount)
            {
                state.Enabled = false;
                return;
            }

            if (mTimer >= generator.TickTime)
            {
                GenerateCube(ref state, generator);
                mTimer -= generator.TickTime;
            }

            mTimer += SystemAPI.Time.DeltaTime;
        }

        void GenerateCube(ref SystemState state, CubeGenerator generator)
        {
            var cubes = CollectionHelper.CreateNativeArray<Entity>(generator.GenerationNumPerTick, Allocator.Temp);
            state.EntityManager.Instantiate(generator.CubeProtoType, cubes);
            foreach (var cube in cubes)
            {
                state.EntityManager.AddComponentData(cube, new RotateSpeed()
                {
                    Value = math.radians(generator.RotateSpeed),
                });
                state.EntityManager.AddComponentData(cube, new MovementSpeed()
                {
                    Value = generator.MoveSpeed,
                });
                //随机目的地
                var random = SystemAPI.GetSingletonRW<RandomSingleton>();
                var randomPos =
                    random.ValueRW.Rand.NextFloat3(-generator.TargetAreaSize * 0.5f, generator.TargetAreaSize * 0.5f);
                state.EntityManager.AddComponentData(cube, new RandomTarget()
                {
                    TargetPos = generator.TargetAreaPos + randomPos,
                });
                //随机生成点
                random = SystemAPI.GetSingletonRW<RandomSingleton>();
                randomPos = random.ValueRW.Rand.NextFloat3(-generator.GeneratorAreaSize * 0.5f,
                    generator.GeneratorAreaSize * 0.5f);
                var pos = generator.GeneratorAreaPos + randomPos;
                var transform = SystemAPI.GetComponentRW<LocalTransform>(cube);
                transform.ValueRW.Position = pos;
            }

            cubes.Dispose();
            mCubesCount += generator.GenerationNumPerTick;
        }
    }
}